<?php

namespace app\admin\controller;

use app\admin\model\Order;
use app\admin\model\User;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 收货地址管理
 *
 * @icon fa fa-circle-o
 */
class Useraddress extends Backend
{

    /**
     * Useraddress模型对象
     * @var \app\admin\model\Useraddress
     */
    protected $model = null;
    protected $noNeedRight = ['import'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Useraddress;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user','gift','orders','selfaddress'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                if ($row['type'] == 1) {
                    $row['address'] = $row['selfaddress']['city'].'-'.$row['selfaddress']['address'];
                } else {
                    $row['address'] = $row['province_id'].$row['city_id'].$row['district_id'].$row['detail'];
                }
                $row->visible(['id','mobile','type','status','user.username','user.number','gift.name','orders.ordernum','address']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }

        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }

        if ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }
        if (!$PHPExcel = $reader->load($filePath)) {
            $this->error('未能正确加载数据');die();
        }
        $sheetData = $PHPExcel->getSheet(0);

        //计算最高行数和列数
        $highestRow = $sheetData->getHighestRow();
        $highestColumn = $sheetData->getHighestColumn();
        $currentRow = 2; //从第2行开始
        $insert = [];
        $userModel = new User();
        $orderModel = new Order();
        try {
            while ($currentRow <= $highestRow) {
                $row = [];
                $rowData = $sheetData->rangeToArray("A$currentRow:$highestColumn$currentRow", '', true, true, true);
                if ($rowData) {
                    $v = $rowData[$currentRow];
                    if (trim($v['A']) && trim($v['B'])) {
//                        $where_sql['username'] = trim($v['A']);
//                        $where_sql['number'] = trim($v['B']);
//                        $user_id = $userModel->where($where_sql)->value('id');
                        $user_id = $this->model
                            ->whereRaw("CONCAT(province_id, city_id, district_id, detail) = '{$v['C']}'")
                            ->where(['mobile'=>$v['B'], 'type'=>2])->value('user_id');
                        if ($user_id && trim($v['A'])) {
                            \app\admin\model\Useraddress::where('user_id', $user_id)->update(['status'=>2]);
                            $row['user_id'] = $user_id;
                            $row['ordernum'] = trim($v['A']);
                            $insert[] = $row;
                        }
                    }
                }
                $currentRow++;
            }
            if ($insert) {
//                dump($insert);die();
                $orderModel->isUpdate(false)->saveAll($insert);
            }
        } catch (ValidateException|PDOException|Exception $e) {
            $msg = $e->getMessage();
            $this->error($msg);
        }

        $this->success();
    }

    public function export()
    {
        if ($this->request->isPost()) {
            Vendor('PHPExcel.PHPExcel');
            $objExcel = new \PHPExcel();

            //标题
            $objExcel->getProperties()->settitle("title");

            //选择当前工作表
            $objActSheet = $objExcel->getActiveSheet();

            $objActSheet->getStyle('B')->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
            $objActSheet->setCellValue('A1', '员工姓名');
            $objActSheet->setCellValue('B1', '工号');
            $objActSheet->setCellValue('C1', '手机号');
            $objActSheet->setCellValue('D1', '收货方式');
            $objActSheet->setCellValue('E1', '状态');
            $objActSheet->setCellValue('F1', '礼盒');
            $objActSheet->setCellValue('G1', '订单编号');
            $objActSheet->setCellValue('H1', '地址');

            $search = $this->request->post('search');
            $ids = $this->request->post('ids');
            $filter = $this->request->post('filter');
            $op = $this->request->post('op');

            $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
            $filter = json_decode($this->request->get('filter'),true);
            //这个是符号 类似这样['game_id'=>'=','name'=>'like']
            $op = json_decode($this->request->get('op'),true);
            //如果你想修改这个，比如去掉name这个条件,像下面这样操作
            if (isset($filter['status'])) {
                $filter['a.status'] = $filter['status'];
                unset($filter['status']);
            }
            $this->request->get(['filter'=>json_encode($filter)]);
            $this->request->get(['op'=>json_encode($op)]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

//            dump($where);die();

            $line = 2;
            $list = $this->model
                ->alias('a')
                ->join('user u', 'a.user_id = u.id', 'LEFT')
                ->join('order o', 'a.user_id = o.user_id', 'LEFT')
                ->join('gift g', 'a.gift_id = g.id', 'LEFT')
                ->join('self_address s', 'a.self_id = s.id', 'LEFT')
                ->where($where)
                ->field([
                    'u.username','u.number'=>'user_number',
                    'a.mobile','a.type','a.province_id','a.city_id', 'a.district_id','a.detail','a.status',
                    's.address', 'g.name','o.ordernum'
                ])
                ->select();
            foreach ($list as $v) {
                $objActSheet->setCellValue('A'.$line, $v['username']);
                $objActSheet->setCellValue('B'.$line, $v['user_number']);
                if ($v['type'] == 1) {
                    $objActSheet->setCellValue('D'.$line, '自提');
                    $objActSheet->setCellValue('H'.$line, $v['address']);
                } elseif ($v['type'] == 2) {
                    $address = $v['province_id'].$v['city_id'].$v['district_id'].$v['detail'];
                    $objActSheet->setCellValue('C'.$line, $v['mobile']);
                    $objActSheet->setCellValue('D'.$line, '邮寄');
                    $objActSheet->setCellValue('H'.$line, $address);
                }
                switch ($v['status']) {
                    case 0:
                        $objActSheet->setCellValue('E'.$line, '未发货');
                        break;
                    case 1:
                        $objActSheet->setCellValue('E'.$line, '已收货');
                        break;
                    case 2:
                        $objActSheet->setCellValue('E'.$line, '已发货');
                        break;
                }
                $objActSheet->setCellValue('F'.$line, $v['name']);
                $objActSheet->setCellValue('G'.$line, $v['ordernum']);
                $line++;
            }
            ob_end_clean();
            header("Content-Type: application/force-download");
            header("Content-Type: application/octet-stream");
            header("Content-Type: application/download");
            header('Content-Disposition:inline;filename="订单'.date('YmdHis').'.xlsx');
            header("Content-Transfer-Encoding: binary");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Pragma: no-cache");
            $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');
            $objWriter->save('php://output');
            exit;
        }
    }

}
